#include "user_api_handler.h"
#include "auth_api_handler.h"
#include "common_user_manager.h"
#include "base_log.h"
#include <nlohmann/json.hpp>
#include <string>
#include <unordered_map>
#include <regex>

namespace El {
namespace Restful {

using json = nlohmann::json;

// 将Common::UserInfo转换为JSON响应格式
json ConvertUserToJson(const Common::UserInfo &user)
{
    return {{"username", user.username},
            {"role", user.role},
            {"status", user.enabled ? "active" : "disabled"},
            {"last_login", user.lastLoginTime}};
}

WebServer::HttpResponse HandleUserList(const WebServer::HttpRequest &req)
{
    (void)req;
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    // 获取用户列表
    std::vector<Common::UserInfo> users;
    if (!Common::UserManager::GetInstance().GetUserList(users)) {
        response.status_code = 500;
        json error = {{"code", 500},
                      {"message", "Failed to get user list"},
                      {"data", nullptr},
                      {"error", "Internal server error"}};
        response.body = error.dump();
        return response;
    }

    // 构造响应
    json data = {{"code", 200}, {"message", "Success"}, {"data", json::array()}, {"error", nullptr}};

    for (const auto &user : users) {
        data["data"].push_back(ConvertUserToJson(user));
    }

    response.status_code = 200;
    response.body = data.dump();
    return response;
}

WebServer::HttpResponse HandleUserCreate(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    try {
        json request_data = json::parse(req.body);

        // 创建用户信息
        Common::UserInfo newUser;
        newUser.username = request_data["username"].get<std::string>();
        newUser.password = request_data["password"].get<std::string>();
        newUser.role = request_data["role"].get<std::string>();
        newUser.enabled = true;
        newUser.lastLoginTime = 0;

        // 创建用户
        if (!Common::UserManager::GetInstance().AddUser(newUser)) {
            response.status_code = 400;
            json error = {{"code", 400},
                          {"message", "Failed to create user"},
                          {"data", nullptr},
                          {"error", "Username already exists or invalid parameters"}};
            response.body = error.dump();
            return response;
        }

        // 构造响应
        json data = {{"code", 200},
                     {"message", "User created successfully"},
                     {"data", ConvertUserToJson(newUser)},
                     {"error", nullptr}};
        response.status_code = 200;
        response.body = data.dump();
    } catch (const std::exception &e) {
        LOG_ERROR("Failed to handle user create request: {}", e.what());
        response.status_code = 400;
        json error = {{"code", 400}, {"message", "Invalid request format"}, {"data", nullptr}, {"error", e.what()}};
        response.body = error.dump();
    }

    return response;
}

WebServer::HttpResponse HandleUserUpdate(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    try {
        // 使用正则表达式从URI中提取用户名
        std::regex pattern("^/v1/users/([^/]+)$");
        std::smatch matches;
        if (!std::regex_match(req.uri, matches, pattern) || matches.size() != 2) {
            throw std::runtime_error("Invalid URI format: missing user ID");
        }
        std::string username = matches[1].str();

        json request_data = json::parse(req.body);

        // 获取现有用户信息
        Common::UserInfo user;
        if (!Common::UserManager::GetInstance().GetUserInfo(username, user)) {
            response.status_code = 404;
            json error = {
                {"code", 404}, {"message", "User not found"}, {"data", nullptr}, {"error", "User does not exist"}};
            response.body = error.dump();
            return response;
        }

        // 更新用户信息
        if (request_data.contains("role")) {
            user.role = request_data["role"].get<std::string>();
        }
        if (request_data.contains("enabled")) {
            user.enabled = request_data["enabled"].get<bool>();
        }

        // 保存更新后的用户信息
        if (!Common::UserManager::GetInstance().UpdateUser(user)) {
            response.status_code = 500;
            json error = {{"code", 500},
                          {"message", "Failed to update user"},
                          {"data", nullptr},
                          {"error", "Internal server error"}};
            response.body = error.dump();
            return response;
        }

        // 构造响应
        json data = {{"code", 200},
                     {"message", "User updated successfully"},
                     {"data", ConvertUserToJson(user)},
                     {"error", nullptr}};
        response.status_code = 200;
        response.body = data.dump();
    } catch (const std::exception &e) {
        LOG_ERROR("Failed to handle user update request: {}", e.what());
        response.status_code = 400;
        json error = {{"code", 400}, {"message", "Invalid request format"}, {"data", nullptr}, {"error", e.what()}};
        response.body = error.dump();
    }

    return response;
}

WebServer::HttpResponse HandleUserDelete(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    try {
        // 使用正则表达式从URI中提取用户名
        std::regex pattern("^/v1/users/([^/]+)$");
        std::smatch matches;
        if (!std::regex_match(req.uri, matches, pattern) || matches.size() != 2) {
            throw std::runtime_error("Invalid URI format: missing user ID");
        }
        std::string username = matches[1].str();

        // 删除用户
        if (!Common::UserManager::GetInstance().DeleteUser(username)) {
            response.status_code = 404;
            json error = {
                {"code", 404}, {"message", "User not found"}, {"data", nullptr}, {"error", "User does not exist"}};
            response.body = error.dump();
            return response;
        }

        // 构造响应
        json data = {{"code", 200}, {"message", "User deleted successfully"}, {"data", nullptr}, {"error", nullptr}};
        response.status_code = 200;
        response.body = data.dump();
    } catch (const std::exception &e) {
        LOG_ERROR("Failed to handle user delete request: {}", e.what());
        response.status_code = 400;
        json error = {{"code", 400}, {"message", "Invalid request format"}, {"data", nullptr}, {"error", e.what()}};
        response.body = error.dump();
    }

    return response;
}

WebServer::HttpResponse HandleUserChangePassword(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    try {
        // 使用正则表达式从URI中提取用户名
        std::regex pattern("^/v1/users/([^/]+)/password$");
        std::smatch matches;
        if (!std::regex_match(req.uri, matches, pattern) || matches.size() != 2) {
            throw std::runtime_error("Invalid URI format: missing user ID");
        }
        std::string username = matches[1].str();

        json request_data = json::parse(req.body);

        std::string newPassword = request_data["new_password"].get<std::string>();
        std::string oldPassword = request_data.value("old_password", "");

        // 修改密码
        if (!Common::UserManager::GetInstance().ChangePassword(username, oldPassword, newPassword)) {
            response.status_code = 404;
            json error = {{"code", 404},
                          {"message", "Failed to change password"},
                          {"data", nullptr},
                          {"error", "User not found or invalid password"}};
            response.body = error.dump();
            return response;
        }

        // 构造响应
        json data = {
            {"code", 200}, {"message", "Password changed successfully"}, {"data", nullptr}, {"error", nullptr}};
        response.status_code = 200;
        response.body = data.dump();
    } catch (const std::exception &e) {
        LOG_ERROR("Failed to handle change password request: {}", e.what());
        response.status_code = 400;
        json error = {{"code", 400}, {"message", "Invalid request format"}, {"data", nullptr}, {"error", e.what()}};
        response.body = error.dump();
    }

    return response;
}

void RegisterUserApiHandlers()
{
    WebServer::IHttpServer &server = WebServer::IHttpServer::GetInstance();

    server.RegisterHandler("GET", "^/v1/users$", HandleUserList);
    server.RegisterHandler("POST", "^/v1/users$", HandleUserCreate);
    server.RegisterHandler("PUT", "^/v1/users/([^/]+)$", HandleUserUpdate);
    server.RegisterHandler("DELETE", "^/v1/users/([^/]+)$", HandleUserDelete);
    server.RegisterHandler("PUT", "^/v1/users/([^/]+)/password$", HandleUserChangePassword);
}

} // namespace Restful
} // namespace El